//
//  NSString+Utils.m
//  LPA_C2C
//
//  Created by HuangYingjie on 15/11/2.
//  Copyright © 2015年 yixin. All rights reserved.
//

#import "NSString+Utils.h"
#import <CommonCrypto/CommonDigest.h>
#include <netdb.h>
#include <arpa/inet.h>

@implementation NSString (Utils)

- (NSString *)md5String
{
    const char *cStr = [self UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cStr, strlen(cStr), result);
    
    NSMutableString *hash = [NSMutableString string];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [hash appendFormat:@"%02X",result[i]];
    }
    return [hash lowercaseString];
}

- (BOOL)isAllDigits
{
    NSCharacterSet *nonNumbers = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    NSRange range = [self rangeOfCharacterFromSet:nonNumbers];
    return range.location == NSNotFound;
}

- (NSString *)trimedString
{
    if (self)
    {
        NSString *trimedStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        return trimedStr;
    }
    
    return self;
}

- (CGSize)boundingRectWithSize:(CGSize)size font:(UIFont *)font
{
    NSDictionary *attributes = @{NSFontAttributeName:font};
    CGSize tsize = [self boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    
    return tsize;
}

//获取拼音首字母(传入汉字字符串, 返回汉字拼音
- (NSString *)yinYinCharactor
{
    // 转成可变字符串
    NSMutableString *str = [[NSMutableString alloc] initWithString:self];
    // 先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    // 再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    // 转化为大写拼音
    NSString *pinYin = [[str trimedString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [pinYin length] > 0 ? [pinYin lowercaseString] : nil;
}

#pragma mark - 根据Attribute返回字符串size
- (CGSize)boundingRectWhitAttributes:(NSDictionary *)attributes AndSize:(CGSize)size
{
    
    if (attributes == nil) {
        UIFont * font = [UIFont systemFontOfSize:15.0];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
        
        attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
    }
    
    CGSize tsize = [self boundingRectWithSize:size
                                      options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  | NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributes
                                      context:nil].size;
    return tsize;
}

#pragma mark-- 替换字符串
- (NSString *)replaceWithstr:(NSString *)str
{
    if(str == nil) return nil;
    NSMutableString *responseString = [NSMutableString stringWithString:str];
    NSString *character = nil;
    for (int i = 0; i < responseString.length; i++) {
        character = [responseString substringWithRange:NSMakeRange(i, 1)];
        if ([character isEqualToString:@"\n"])
            [responseString deleteCharactersInRange:NSMakeRange(i, 1)];
    }
    
    return responseString;
}


/**
 containsString 支持iOS 8及以上系统，该方法是兼容iOS 7

 @param string
 @return
 */
- (BOOL)containsSomeString:(NSString *)string
{
    if ([self isBlankString:string]) {
        return NO;
    }
    
    if (!([self rangeOfString:string].location == NSNotFound)){
        return YES;
    }else{
        return NO;
    }
}


/**
 判断字符串是否为空

 @param string
 @return
 */
- (BOOL)isBlankString:(NSString *)string
{
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
    }
    
    return NO;
    
}

/**
 正则表达式 判断密码强度

 @param regex 正则表达式
 @return
 */
- (BOOL)isValidateByRegex:(NSString *)regex{
    NSPredicate *pre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pre evaluateWithObject:self];
}

/**
 返回ip地址 self为domain

 @return
 */
- (NSString *)getIpAddress
{
    struct hostent *hs;
    struct sockaddr_in server;
    if ((hs = gethostbyname([self UTF8String])) != NULL)
    {
        server.sin_addr = *((struct in_addr*)hs->h_addr_list[0]);
        return [NSString stringWithUTF8String:inet_ntoa(server.sin_addr)];
    }
    return nil;
}

- (CGSize)sizeWithBoundingRectSize:(CGSize)rectSize attributeFont:(UIFont *)attributeFont {
    
    if ([self isKindOfClass:[NSNull class]] || self.length == 0) {
        return CGSizeZero;
    }
    
    NSDictionary *attributes = @{NSFontAttributeName: attributeFont};
    
    CGSize stringSize = [self boundingRectWithSize:rectSize
                                           options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                        attributes:attributes
                                           context:nil].size;
    
    return CGSizeMake(ceilf(stringSize.width), ceilf(stringSize.height));
}
//处理价格
+ (NSString *)handlePrice:(double)price
{
    long computePrice = (long)price/100;
    return [NSString stringWithFormat:@"Ks%ld",computePrice];
}

@end
